<?php

namespace App\Http\Middleware;

use App\Exceptions\lin\TokenException;
use App\Lib\auth\AuthMap;
use App\Services\token\LoginToken;
use Closure;
use Illuminate\Http\Request;

class JwtAuth
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws TokenException
     */
    public function handle(Request $request, Closure $next)
    {
        $jwtAuth = LoginToken::getInstance();
        if ($jwtAuth->verify()) {
            $actions = $request->route()->getAction();//路由权限
            if (!empty($actions['auth'])) {//有权限
                $route = (new AuthMap())->checkUserAuth($actions['auth']);
                if ($route) return $next($request);

                throw new TokenException(10001);
            }
            return $next($request);
        } else {
            throw new TokenException();
        }
    }
}
